<template>
  <div id="userManagePage">
    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="false">
      <template #title>
        <SearchOutlined class="card-icon" />
        搜索筛选
      </template>
      <a-form :model="searchParams" layout="inline" @finish="doSearch" class="search-form">
        <a-form-item label="账号">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="请输入账号"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <UserOutlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="用户名">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="请输入用户名"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <UserOutlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="请选择用户角色"
            allow-clear
            class="search-select"
          >
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button html-type="submit" type="primary" class="search-btn">
              <SearchOutlined />
              搜索
            </a-button>
            <a-button @click="resetSearch" class="reset-btn">
              <ReloadOutlined />
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <TableOutlined class="card-icon" />
        用户列表
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showAddModal" class="add-btn">
            <PlusOutlined />
            新增用户
          </a-button>
          <a-button @click="fetchData" class="refresh-btn">
            <ReloadOutlined />
            刷新
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :loading="loading"
        @change="doTableChange"
        class="user-table"
        :scroll="{ x: 1200 }"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userAvatar'">
            <ImagePreview
              :image-url="record.userAvatar"
              :alt="`${record.userName} 的头像`"
              :title="`${record.userName} 的头像`"
            >
              <a-avatar :src="record.userAvatar" :size="40" class="user-avatar">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </ImagePreview>
          </template>
          <template v-else-if="column.dataIndex === 'userRole'">
            <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
              {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            <span class="time-text">
              {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'userProfile'">
            <a-tooltip :title="record.userProfile" placement="topLeft">
              <span class="profile-text">
                {{ record.userProfile || '暂无简介' }}
              </span>
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="showEditModal(record)" class="edit-btn">
                <EditOutlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="doDelete(record.id)"
              >
                <a-button danger size="small" class="delete-btn">
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑用户模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      :title="editingUser.id ? '编辑用户' : '新增用户'"
      width="600px"
      :confirm-loading="editLoading"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      class="edit-modal"
    >
      <a-form
        ref="editFormRef"
        :model="editingUser"
        :rules="editRules"
        layout="vertical"
        class="edit-form"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名" name="userName">
              <a-input v-model:value="editingUser.userName" placeholder="请输入用户名">
                <template #prefix>
                  <UserOutlined class="input-icon" />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="账号" name="userAccount">
              <a-input
                v-model:value="editingUser.userAccount"
                placeholder="请输入账号"
                :disabled="!!editingUser.id"
              >
                <template #prefix>
                  <UserOutlined class="input-icon" />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="用户头像" name="userAvatar">
          <a-input v-model:value="editingUser.userAvatar" placeholder="请输入头像URL">
            <template #prefix>
              <PictureOutlined class="input-icon" />
            </template>
          </a-input>
          <div class="avatar-preview" v-if="editingUser.userAvatar">
            <a-avatar :src="editingUser.userAvatar" :size="80">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
          </div>
        </a-form-item>

        <a-form-item label="用户角色" name="userRole">
          <a-select v-model:value="editingUser.userRole" placeholder="请选择用户角色">
            <a-select-option value="user">
              <UserOutlined />
              普通用户
            </a-select-option>
            <a-select-option value="admin">
              <CrownOutlined />
              管理员
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="用户简介" name="userProfile">
          <a-textarea
            v-model:value="editingUser.userProfile"
            placeholder="请输入用户简介"
            :rows="3"
            show-count
            :maxlength="200"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUser, listUserVoByPage, updateUser, addUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import type { FormInstance } from 'ant-design-vue'
import {
  SearchOutlined,
  UserOutlined,
  TableOutlined,
  PlusOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  CrownOutlined,
  PictureOutlined,
} from '@ant-design/icons-vue'
import ImagePreview from '@/components/ImagePreview.vue'

const columns = [
  {
    title: '编号',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 展示的数据
const data = ref<API.UserVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 编辑相关状态
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editingUser = reactive<API.UserUpdateRequest & API.UserAddRequest>({
  id: undefined,
  userName: '',
  userAccount: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
})

// 表单验证规则
const editRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', trigger: 'blur' },
  ],
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 16, message: '账号长度为4-16个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '账号只能包含字母、数字和下划线', trigger: 'blur' },
  ],
  userRole: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPage({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch {
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格分页变化时的操作
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    pageNum: 1,
    pageSize: 10,
    userAccount: undefined,
    userName: undefined,
    userRole: undefined,
  })
  fetchData()
}

// 显示新增模态框
const showAddModal = () => {
  Object.assign(editingUser, {
    id: undefined,
    userName: '',
    userAccount: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user',
  })
  editModalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record: API.UserVO) => {
  Object.assign(editingUser, {
    id: record.id,
    userName: record.userName,
    userAccount: record.userAccount,
    userAvatar: record.userAvatar,
    userProfile: record.userProfile,
    userRole: record.userRole,
  })
  editModalVisible.value = true
}

// 处理编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value?.validate()
    editLoading.value = true

    if (editingUser.id) {
      // 编辑用户
      const res = await updateUser({
        id: editingUser.id,
        userName: editingUser.userName,
        userAvatar: editingUser.userAvatar,
        userProfile: editingUser.userProfile,
        userRole: editingUser.userRole,
      })
      if (res.data.code === 0) {
        message.success('编辑用户成功')
        editModalVisible.value = false
        await fetchData()
      } else {
        message.error('编辑用户失败：' + res.data.message)
      }
    } else {
      // 新增用户
      const res = await addUser({
        userName: editingUser.userName,
        userAccount: editingUser.userAccount,
        userAvatar: editingUser.userAvatar,
        userProfile: editingUser.userProfile,
        userRole: editingUser.userRole,
      })
      if (res.data.code === 0) {
        message.success('新增用户成功')
        editModalVisible.value = false
        await fetchData()
      } else {
        message.error('新增用户失败：' + res.data.message)
      }
    }
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    editLoading.value = false
  }
}

// 处理编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除数据
const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  try {
    const res = await deleteUser({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      await fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch {
    message.error('删除失败')
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
#userManagePage {
  margin: 0 auto;
  padding: 16px 24px;
}

/* 卡片样式 */
.search-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.search-card .ant-card-head,
.table-card .ant-card-head {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.card-icon {
  margin-right: 8px;
  color: #6c5ce7;
}

/* 搜索表单 */
.search-form {
  padding: 8px 0;
}

.search-input,
.search-select {
  width: 200px;
}

.input-icon {
  color: #bfbfbf;
}

.search-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 8px rgba(108, 92, 231, 0.3);
}

.reset-btn {
  border-color: #d9d9d9;
}

.reset-btn:hover {
  border-color: #6c5ce7;
  color: #6c5ce7;
}

/* 表格样式 */
.user-table {
  background: white;
}

.user-table .ant-table-thead > tr > th {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 8px 16px;
}

.user-table .ant-table-tbody > tr > td {
  padding: 8px 16px;
  vertical-align: middle;
}

.user-table .ant-table-tbody > tr:hover > td {
  background: rgba(108, 92, 231, 0.04);
}

/* 头像样式 */
.user-avatar {
  border: 2px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.time-text {
  color: #666;
  font-size: 13px;
}

.profile-text {
  color: #666;
  max-width: 200px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 操作按钮 */
.edit-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3);
}

.edit-btn:hover {
  background: linear-gradient(135deg, #7c6ce8, #6c5ce7);
  transform: translateY(-1px);
}

/* 新增按钮 */
.add-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3);
}

.add-btn:hover {
  background: linear-gradient(135deg, #7c6ce8, #6c5ce7);
  transform: translateY(-1px);
}

/* 刷新按钮 */
.refresh-btn {
  border-color: #6c5ce7;
  color: #6c5ce7;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background: rgba(108, 92, 231, 0.06);
  border-color: #6c5ce7;
  color: #6c5ce7;
  transform: translateY(-1px);
}

.delete-btn {
  box-shadow: 0 2px 6px rgba(255, 77, 79, 0.3);
}

.delete-btn:hover {
  transform: translateY(-1px);
}

/* 编辑模态框 */
.edit-modal .ant-modal-header {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border-radius: 8px 8px 0 0;
}

.edit-modal .ant-modal-title {
  color: white;
  font-weight: 600;
}

.edit-form {
  padding: 16px 0;
}

.edit-form .ant-form-item-label > label {
  font-weight: 600;
  color: #262626;
}

.avatar-preview {
  margin-top: 12px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  #userManagePage {
    max-width: 100%;
    padding: 16px 20px;
  }
}

@media (max-width: 768px) {
  #userManagePage {
    padding: 12px 16px;
  }

  .search-input,
  .search-select {
    width: 160px;
  }

  .search-form .ant-form-item {
    margin-bottom: 16px;
  }

  .search-card,
  .table-card {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  #userManagePage {
    padding: 8px 12px;
  }

  .search-input,
  .search-select {
    width: 140px;
  }
}

/* 紫色主题色定义 */
:root {
  --primary-color: #6c5ce7;
  --primary-hover: #7c6ce8;
  --primary-dark: #5a4fcf;
  --primary-light: rgba(108, 92, 231, 0.06);
}

/* 动画效果 */
.search-btn,
.reset-btn,
.edit-btn,
.delete-btn,
.add-btn,
.refresh-btn {
  transition: all 0.3s ease;
}

.user-table .ant-table-tbody > tr {
  transition: background-color 0.3s ease;
}

.search-card,
.table-card {
  transition: box-shadow 0.3s ease;
}

.search-card:hover,
.table-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}
</style>
